<template>
    <div class="img-up">
        <div class="img-box">
            <div class="img-item" v-for="(item, index) in fileArr" :key="index" @click.stop.prevent="FullScreen(index)">
                <video
                    @canplay="canplay(index)"
                    @loadeddata="loadeddata"
                    :id="field + index"
                    :src="previewUrl + item"
                    style="display: none"
                    preload
                ></video>
                <i v-if="!disabled" class="el-icon-delete delete-icon" @click.stop="del(index)"></i>
                <i class="f16 el-icon-loading"></i>
            </div>

            <div class="img-item" @click.capture="inputPreClick" v-if="!disabled">
                <input
                    id="uploaderInput"
                    v-if="showInput"
                    ref="inputImg"
                    type="file"
                    accept="video/*"
                    capture="camera"
                    @change.capture="uploadMulFile"
                />
                <i class="el-icon-camera f32" />
            </div>
        </div>
    </div>
</template>
<!--audio/* 表示音频文件 HTML5-->
<!--video/* 表示视频文件 HTML5-->
<!--image/* 表示图片文件 HTML5-->
<script>
import axios from 'axios'
import url from '@/common/url-config'
import { getFileToken } from '@/common/api/common'
const { fileBaseUrl, videoPreviewUrl } = url
let me

export default {
    name: 'ImgUp',
    data() {
        return {
            previewUrl: fileBaseUrl + videoPreviewUrl,
            fileArr: [],
            uploadFile: [],
            showInput: true, //用于解决change事件触发一次之后，再次选择图片，偶尔不触发的情况
            currentVideo: null,
            loading: null,
        }
    },
    computed: {
        disabled() {
            return this.$attrs.disabled
        },
        field() {
            return this.$attrs.__vModel__
        },
    },
    mounted() {
        me = this
        let val = this.$vnode.data.props.value
        if (val) {
            this.fileArr = JSON.parse(val)
        }
    },
    destroyed() {
        this.loading = null
    },
    methods: {
        inputClick() {
            console.log(111)
        },
        canplay(index) {
            console.log(1)
            let id = this.field + index
            document.querySelector(`#${id} ~ .el-icon-loading`).style.display = 'none'
            document.querySelector(`#${id}`).style.display = 'block'
        },
        loadeddata() {
            console.log(2)
        },
        //进入全屏
        FullScreen(index) {
            let key = this.field + index
            let ele = document.getElementById(key)
            this.currentVideo = ele
            if (ele.requestFullscreen) {
                ele.requestFullscreen()
            } else if (ele.mozRequestFullScreen) {
                ele.mozRequestFullScreen()
            } else if (ele.webkitRequestFullScreen) {
                ele.webkitRequestFullScreen()
            }
            //若不延时，会监听到第一进入全屏事件
            let time = 0
            let interval = setInterval(() => {
                time++
                if (time > 5) {
                    clearInterval(interval)
                }
                if (this.checkFull()) {
                    window.addEventListener('resize', this.pause)
                    clearInterval(interval)
                }
            }, 100)
        },
        pause() {
            if (!this.checkFull()) {
                this.currentVideo.pause()
                this.currentVideo = null
                window.removeEventListener('resize', this.pause)
            }
        },
        checkFull() {
            var isFull =
                document.fullscreenEnabled ||
                window.fullScreen ||
                document.webkitIsFullScreen ||
                document.msFullscreenEnabled
            if (isFull === undefined) isFull = false
            return isFull
        },
        //退出全屏
        exitFullscreen() {
            var de = document
            if (de.exitFullscreen) {
                de.exitFullscreen()
            } else if (de.mozCancelFullScreen) {
                de.mozCancelFullScreen()
            } else if (de.webkitCancelFullScreen) {
                de.webkitCancelFullScreen()
            }
        },
        del(index) {
            this.fileArr.splice(index, 1)
        },
        async readyUpload() {
            let fileToken = this.fileToken
            let uploadFile = this.uploadFile
            let fileIndex = 0
            const reader = new FileReader()
            reader.readAsBinaryString(uploadFile[fileIndex]) //读法异步的
            reader.onloadend = async () => {
                // 这个事件在读取结束后，无论成功或者失败都会触发
                if (reader.error) {
                    // console.log(reader.error)
                    this.$message.error(`读取文件错误，原因：${reader.error}`)
                } else {
                    if (fileIndex < uploadFile.length) {
                        reader.readAsBinaryString(uploadFile[fileIndex]) //读法异步的
                        me.uploadFileServer(fileToken, uploadFile[fileIndex], fileIndex)
                        fileIndex++
                    } else {
                        setTimeout(() => {
                            me.showInput = true
                        })
                    }
                }
            }
        },
        async uploadFileServer(token, file, fileIndex) {
            const uploadFile = new FormData()
            uploadFile.append('file', file)
            try {
                let res = await axios({
                    method: 'post',
                    url: '/file/api/Upload/v1/Single',
                    headers: { 'Content-Type': 'multipart/form-data', token },
                    data: uploadFile,
                })
                if (res.data.code == 200) {
                    this.fileArr.push(res.data.data.id)
                }
            } catch (e) {
                console.log(e)
            }
            if (fileIndex + 1 === this.uploadFile.length) {
                this.$emit('input', JSON.stringify(this.fileArr))
            }
            this.loading.close()
        },
        inputPreClick(e) {
            if (this.fileArr.length >= this.$attrs.imgNumber) {
                e.stopPropagation()
                e.preventDefault()
                return this.$message({
                    type: 'error',
                    message: '视频允许最大数量为' + this.$attrs.imgNumber,
                    duration: 2 * 1000,
                })
            }
        },
        async uploadMulFile(e) {
            const me = this
            this.showInput = false
            let uploadFile = document.getElementById('uploaderInput').files
            // let url = URL.createObjectURL(uploadFile)

            if (this.fileArr.length + uploadFile.length > this.$attrs.imgNumber) {
                setTimeout(() => {
                    me.showInput = true
                })
                return this.$message({
                    type: 'error',
                    message: '视频允许最大数量为' + this.$attrs.imgNumber,
                    duration: 2 * 1000,
                })
            }

            this.uploadFile = uploadFile
            this.loading = this.$loading({
                lock: true,
                text: '正在上传视频...',
            })
            try {
                let res = await getFileToken()
                this.fileToken = res?.data?.token
                this.readyUpload()
            } catch (e) {
                console.log(e)
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.img-up {
    width: 100%;
    position: relative;
    font-size: 60px;
    input {
        position: absolute;
        opacity: 0;
        width: 75px;
        height: 75px;
    }
    .img-box {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        flex-wrap: wrap;
        .img-item {
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            margin-right: 10px;
            margin-bottom: 10px;
            width: 75px;
            height: 75px;
            opacity: 1;
            background: #ffffff;
            border: 2px dashed #d3e5ff;
            border-radius: 11px;
            > video {
                max-width: 100%;
                height: 100%;
            }
            .delete-icon {
                color: #666;
                font-size: 16px;
                position: absolute;
                top: -8px;
                right: -8px;
            }
        }
    }
}
</style>
